// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    const BASE_URL = window.BASE_URL || '/AVR'; // 项目基础路径
    const servicesContainer = document.getElementById('services-container');
    const modal = document.getElementById('service-modal');
    const closeModal = document.getElementById('close-modal');
    const applyFilterBtn = document.getElementById('apply-filter');
    const resetFilterBtn = document.getElementById('reset-filter');

    // 获取所有陪玩服务 - 对应 @GetMapping("/all")
    async function fetchAllServices() {
        try {
            const response = await fetch(`${BASE_URL}/accompanys/all`);

            // 检查响应状态
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }

            const result = await response.json();

            // 根据 Result 类结构解析响应
            if (result.code === 20011) { // Code.selectALL_OK
                return result.data;
            } else {
                throw new Error(result.msg || '获取数据失败');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showErrorToast(`数据加载失败: ${error.message}`);
            return [];
        }
    }

    // 根据条件筛选陪玩服务 - 对应 @GetMapping("/search")
    async function fetchFilteredServices(params) {
        try {
            // 构建查询参数 - 匹配 @RequestParam 注解
            const queryParams = new URLSearchParams();

            // 只添加有值的参数
            if (params.gameType) queryParams.append('gameType', params.gameType);
            if (params.serviceType) queryParams.append('serviceType', params.serviceType);
            if (params.minPrice) queryParams.append('minPrice', params.minPrice);
            if (params.maxPrice) queryParams.append('maxPrice', params.maxPrice);
            if (params.keyword) queryParams.append('keyword', params.keyword);
            if (params.status) queryParams.append('status', params.status);

            const url = `${BASE_URL}/accompanys/search?${queryParams.toString()}`;
            const response = await fetch(url);

            // 检查响应状态
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }

            const result = await response.json();

            // 根据 Result 类结构解析响应
            if (result.code === 20021) { // Code.selectByConditions_OK
                return result.data;
            } else {
                throw new Error(result.msg || '筛选失败');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showErrorToast(`筛选失败: ${error.message}`);
            return [];
        }
    }

    // 渲染服务卡片
    function renderServices(services) {
        servicesContainer.innerHTML = '';

        if (services.length === 0) {
            servicesContainer.innerHTML = `
                <div class="no-results">
                    <i class="fas fa-search"></i>
                    <h3>没有找到匹配的陪玩服务</h3>
                    <p>请尝试调整筛选条件</p>
                </div>
            `;
            return;
        }

        services.forEach(service => {
            // 处理图片URL - 如果imageUrls是字符串，转换为数组
            const images = typeof service.imageUrls === 'string'
                ? service.imageUrls.split(',')
                : service.imageUrls || [];

            const firstImage = images[0] || 'https://via.placeholder.com/300x200?text=No+Image';

            const card = document.createElement('div');
            card.className = 'service-card';
            card.innerHTML = `
                <div class="card-image">
                    <img src="${firstImage}" alt="${service.gameType}陪玩">
                    <div class="card-badge">${service.serviceType}</div>
                </div>
                <div class="card-content">
                    <h3 class="card-title">${service.gameType}专业陪玩</h3>
                    <div class="card-meta">
                        <span class="game-type">${service.gameType}</span>
                        <span class="service-type">${service.serviceType}</span>
                    </div>
                    <div class="card-price">￥${service.price.toFixed(2)} <span class="price-unit">/小时</span></div>
                    <p class="card-description">${service.description.substring(0, 80)}...</p>
                    <div class="voice-player">
                        <div class="play-btn" data-audio="${service.audioUrl}">
                            <i class="fas fa-play"></i>
                        </div>
                        <div class="voice-info">
                            <div>语音介绍</div>
                            <p>点击播放按钮</p>
                        </div>
                    </div>
                    <div class="card-footer">
                        <a href="#" class="view-details" data-id="${service.id}">查看详情</a>
                        <div class="rating">
                            <i class="fas fa-star"></i> 4.9
                        </div>
                    </div>
                </div>
            `;
            servicesContainer.appendChild(card);
        });

        // 添加查看详情事件监听
        document.querySelectorAll('.view-details').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const serviceId = this.getAttribute('data-id');
                openServiceModal(serviceId, services);
            });
        });

        // 添加语音播放事件
        document.querySelectorAll('.play-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const audioUrl = this.getAttribute('data-audio');
                playAudio(audioUrl);
            });
        });
    }

    // 播放语音
    function playAudio(url) {
        if (!url) {
            showErrorToast('语音介绍不可用');
            return;
        }

        // 处理相对路径的音频URL
        const fullAudioUrl = url.startsWith('http') ? url : `${BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`;

        try {
            const audio = new Audio(fullAudioUrl);
            audio.play().catch(e => {
                console.error('播放失败:', e);
                showErrorToast('播放失败: 请检查音频地址');
            });
        } catch (e) {
            console.error('音频创建失败:', e);
            showErrorToast('音频格式不支持');
        }
    }

    // 打开服务详情模态框
    function openServiceModal(serviceId, services) {
        const service = services.find(s => s.id === parseInt(serviceId));
        if (service) {
            // 处理图片URL - 如果imageUrls是字符串，转换为数组
            const images = typeof service.imageUrls === 'string'
                ? service.imageUrls.split(',')
                : service.imageUrls || [];

            document.getElementById('modal-title').textContent = `${service.gameType}专业陪玩 - ${service.serviceType}`;
            document.getElementById('modal-price').textContent = `￥${service.price.toFixed(2)}`;
            document.getElementById('modal-game-type').textContent = service.gameType;
            document.getElementById('modal-service-type').textContent = service.serviceType;
            document.getElementById('modal-description').textContent = service.description;
            document.getElementById('modal-contact').textContent = service.contact;
            document.getElementById('modal-image').src = images[0] || 'https://via.placeholder.com/600x400?text=No+Image';

            // 更新语音播放按钮
            const voiceBtn = document.querySelector('.modal-voice .play-btn');
            voiceBtn.setAttribute('data-audio', service.audioUrl);

            modal.style.display = 'flex';
        }
    }

    // 显示错误提示
    function showErrorToast(message) {
        // 移除现有的提示
        const existingToast = document.getElementById('error-toast');
        if (existingToast) existingToast.remove();

        // 创建新的提示
        const toast = document.createElement('div');
        toast.id = 'error-toast';
        toast.className = 'error-toast';
        toast.innerHTML = `
            <i class="fas fa-exclamation-circle"></i>
            <span>${message}</span>
        `;

        document.body.appendChild(toast);

        // 3秒后自动消失
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 关闭模态框
    closeModal.addEventListener('click', function() {
        modal.style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });

    // 模态框内的语音播放
    document.querySelector('.modal-voice .play-btn').addEventListener('click', function() {
        const audioUrl = this.getAttribute('data-audio');
        playAudio(audioUrl);
    });

    // 初始化加载数据
    async function init() {
        try {
            const services = await fetchAllServices();
            renderServices(services);
        } catch (error) {
            console.error('初始化失败:', error);
        }
    }

    init();

    // 筛选按钮事件
    applyFilterBtn.addEventListener('click', async function() {
        const gameType = document.getElementById('game-type').value;
        const serviceType = document.getElementById('service-type').value;
        const minPrice = document.getElementById('min-price').value;
        const maxPrice = document.getElementById('max-price').value;
        const keyword = document.getElementById('keyword').value;

        // 构建参数对象 - 匹配后端 @RequestParam 注解
        const params = {};
        if (gameType) params.gameType = gameType;
        if (serviceType) params.serviceType = serviceType;
        if (minPrice) params.minPrice = parseFloat(minPrice);
        if (maxPrice) params.maxPrice = parseFloat(maxPrice);
        if (keyword) params.keyword = keyword;
        params.status = 0; // 只显示已上架的服务

        try {
            const filtered = await fetchFilteredServices(params);
            renderServices(filtered);
        } catch (error) {
            console.error('筛选失败:', error);
        }
    });

    // 重置按钮事件
    resetFilterBtn.addEventListener('click', async function() {
        document.getElementById('game-type').value = '';
        document.getElementById('service-type').value = '';
        document.getElementById('min-price').value = '';
        document.getElementById('max-price').value = '';
        document.getElementById('keyword').value = '';

        try {
            const services = await fetchAllServices();
            renderServices(services);
        } catch (error) {
            console.error('重置失败:', error);
        }
    });

    window.BASE_URL = BASE_URL;
    window.showErrorToast = showErrorToast;
    window.fetchAllServices = fetchAllServices;
    window.renderServices = renderServices;

});